<?php
namespace app\admin\controller;

use think\Controller;

class Policy extends Controller
{
	public function index()
	{
		$keyword = trim(input('get.keyword'));
		if ($keyword != '' ||$keyword != false){
			$policy_list = db('policy')->field(['id','policy','if_publish','created'])->where('policy','like','%'.$keyword.'%')->order('created','desc')->paginate();
		}else{
			$policy_list = db('policy')->field(['id','policy','if_publish','created'])->order('created','desc')->paginate();
		}
		$page = $policy_list->render();
		$policy_list = $policy_list->toArray()['data'];
		foreach ($policy_list as $pk => &$pv){
			$pv['created'] = date('Y-m-d',$pv['created']);
			if ($pv['if_publish'] == '1'){
				$pv['if_publish'] = 'on';
			}else {
				$pv['if_publish'] = 'off';
			}
		}
		$this->assign('policy_list',$policy_list);
		$this->assign('page',$page);
		return $this->fetch('index');
	}

	public function save_policy_view()
    {
        $policy_id = trim(input('get.policy_id'));
        $warehouse_model = model('Warehouse');
        $warehouse_list = $warehouse_model->getAllWarehouse();
        if (empty($policy_id) || $policy_id == false){
            $action = 'add';
        }else{
            $action = 'edit';
            $policy_info = db('policy')->field(['id','policy','created','createdwho','content','attachments','to_where'])->where('id',$policy_id)->find();
            $policy_info['created'] = date('Y-m-d',$policy_info['created']);
            $policy_info['attachments'] = json_decode($policy_info['attachments'],true);
            $policy_info['to_where'] = json_decode($policy_info['to_where']);
            foreach ($warehouse_list as $wk => &$wv){
                if(in_array($wv['id'],$policy_info['to_where'])){
                    $wv['selected'] = '1';
                }else{
                    $wv['selected'] = '0';
                }
            }
            $this->assign('policy',$policy_info);
        }
        $this->assign('warehouse_list',$warehouse_list);
        $this->assign('action',$action);
        return $this->fetch('save');
    }

    public function upload_attachements()
    {
        $result = array('err' => '1','content' => '','file' => array());
        $files = request()->file('attachments_file');
        
        if (is_array($files)){
            $error = false;
            foreach ($files as $file) {
                $file_name = $file->getInfo();
                $file_name = $file_name['name'];
                $file_name = iconv('utf-8', 'gb2312', $file_name);
                $info = $file->move(ROOT_PATH . 'Uploads' . DS . 'policy_temp', $file_name);
                $file_name = iconv('gb2312', 'utf-8', $file_name);
                if ($info->getError()) {
                    $result['content'] .= ' 上传' . $file_name . '失败！';
                    $error = true;
                    continue;
                }else{
                    $file_info = [
                        'file_name' => $file_name,
                        'file_path' => iconv('gb2312', 'utf-8', $info->getSaveName())
                    ];
                }
                array_push($result['file'], $file_info);
                if ($error){
                    return json_encode($result,true);
                }
            }
        }else{
            $file_name = $files->getInfo();
            $file_name = $file_name['name'];
            $file_name = iconv('utf-8','gb2312',$file_name);
            $info = $files->move(ROOT_PATH.'Uploads'.DS.'policy_temp',$file_name);
            if ($info->getError()){
                $result['content'] = '上传失败';
                return json_encode($result,true);
            }else{
                $file_info['file_name'] = iconv('gb2312', 'utf-8', $file_name);
                $file_info['file_path'] = iconv('gb2312', 'utf-8', $info->getSaveName());
                array_push($result['file'], $file_info);
            }
    
        }
        $result['err'] = '0';
        $result['content'] = '上传成功!';
        return json_encode($result,true);
    }
    
   public function save_policy()
   {
   	$result = array('err' => '1','content' => '');
    $policy_info = array();
    $policy_info['id'] = trim(input('post.policy_id'));
    $policy_info['policy'] = trim(input('post.policy_name'));
    $policy_info['content'] = trim(input('post.policy_content'));
    $policy_info['to_where'] = json_encode(input('post.policy_to_where/a'));
    $policy_info['attachments'] = input('post.policy_attachments/a') ? input('post.policy_attachments/a'):array()  ;
    if (empty($policy_info['policy']) || $policy_info['policy'] == null){
           $result['content'] = '文件名不能为空！';
           return $result;
    }
    
    $model = model('Policy');
    if ($policy_info['id'] == '' || $policy_info['id'] == null){
       $policy_info['createdwho'] = session('user_id','','admin');
       foreach ($policy_info['attachments'] as $ak => $av){
           $oldname = iconv('utf-8','gb2312',ROOT_PATH.'Uploads'.DS.'policy_temp'.DS.$av['path']);
           $newname = iconv('utf-8','gb2312',ROOT_PATH.'Uploads'.DS.'policy'.DS.$av['path']);
           if (file_exists($newname)){
               $result['content'] .= $av['name'].'已保存过！ ';
               continue;
           }
           $move_file = rename($oldname,$newname);
//           $move_file = rename(ROOT_PATH.'Uploads'.DS.'policy_temp'.DS.$av['path'],ROOT_PATH.'Uploads'.DS.'policy'.DS.$av['path']);
           if ($move_file == false){
               $result['content'] .= $av['name'].'保存文件失败！ ';
               continue;
           }
       }

    }else{
    	
        $policy_info['attachments'] = $model->reorganizeAttachments($policy_info['attachments'],$policy_info['id']);
    }

    $policy_info['attachments'] = json_encode($policy_info['attachments'],JSON_UNESCAPED_UNICODE);

    $save_policy = $model->savePolicy($policy_info);
    if ($save_policy == false){
        $result['content'] .= '文件保存失败！';
        return $result;
    }
   	$result['err'] = '0';
   	$result['content'] .= '文件保存成功！';
   	return $result;
   }
   
   public function update_if_publish()
   {
   	$result = array('err' => '1','content' => '');
   	$policy_id = input('get.policy_id');
   	$policy_list = array();
   	$policy_list['if_publish'] = trim(input('get.if_publish'));
   	$update_if_publish = db('policy')->where('id',$policy_id)->update($policy_list);
   	if ($update_if_publish == false){
   		$result['content'] = '发布状态更新错误！';
   		return $result;
   	}
   	$result['err'] = '0';
   	$result['content'] = '发布状态更新成功！';
   	return $result;
   }

   public function del_policy()
   {
       $result = array('err' => '1','content' => '');
       $id = trim(input('post.id'));
       $model = model('Policy');
       $del_attachments = $model->delAttachmentsByPolictId($id);
       if ($del_attachments['err'] != '0'){
       		$result['content'] = $del_attachments['content'];
       		return $result;
       }
       $del_policy = db('policy')->where('id',$id)->delete();
       if ($del_policy == false){
           $result['content'] = '删除文件失败！';
           return $result;
       }
       $result['err'] = '0';
       $result['content'] .= '删除文件成功！';
       return $result;
   }

   public function delete_attachment()
   {
       $result = array('err' => '1','content' =>'');
       $policy_id = trim(input('post.policy_id'));
       $policy_path = trim(input('post.attachments_path'));
       if (empty($policy_id) || $policy_id == null){
           $path_prefix = ROOT_PATH.'Uploads'.DS.'policy_temp'.DS;
           $file_name = iconv('utf-8','gb2312',$path_prefix.$policy_path);
           if (!file_exists($file_name)){
               $result['err'] = '0';
               $result['content'] = '文件已删除！';
               return $result;
           }
           unlink($file_name);
       }else{
            $model = model('Policy');
            $del_attachments = $model->del_attachments($policy_id, $policy_path);
            if ($del_attachments['result'] == false){
                $result['content'] = $del_attachments['message'];
                return $result;
            }
            $result['err'] = '0';
            $result['content'] = $del_attachments['message'];
            if (empty($del_attachments)){
                foreach ($del_attachments['info'] as $ak => $av){
                    $result['content'] .= ' '.$av['policy'];
                }
            }
            return $result;
       }
   }
   

 
	
}